<script setup>
import { ref, reactive, watch } from 'vue'
import request from '../../utils/sj-request'

const props = defineProps({
  subjectId: {
    type: Number,
    required: true
  },
  knowledgePoint: {
    type: Object,
    default: () => ({
      id: null,
      parentId: 0,
      subjectId: null,
      name: '',
      sortOrder: 0
    })
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['success', 'cancel'])

// 表单数据
const formData = reactive({
  id: null,
  parentId: 0,
  subjectId: props.subjectId,
  name: '',
  sortOrder: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入知识点名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  sortOrder: [
    { type: 'number', message: '排序号必须为数字', trigger: 'blur' }
  ]
}

// 父级知识点选项
const parentOptions = ref([])
// 加载状态
const loading = ref(false)
// 表单引用
const formRef = ref(null)

// 获取父级知识点选项
const fetchParentOptions = async () => {
  loading.value = true
  try {
    const res = await request({
      url: 'knowledge-point/tree',
      method: 'get',
      params: {
        subjectId: props.subjectId
      }
    })
    
    if (res.code === 200) {
      // 构建选项树
      parentOptions.value = [{ id: 0, name: '顶级知识点', children: [] }]
      if (res.data && res.data.length > 0) {
        // 如果是编辑模式，需要过滤掉当前节点及其子节点
        if (props.isEdit && props.knowledgePoint.id) {
          const filteredData = filterSelfAndChildren(res.data, props.knowledgePoint.id)
          parentOptions.value[0].children = filteredData
        } else {
          parentOptions.value[0].children = res.data
        }
      }
    } else {
      ElMessage.warning(res.message || '获取父级知识点选项失败')
    }
  } catch (error) {
    console.error('获取父级知识点选项失败:', error)
    ElMessage.error('获取父级知识点选项失败')
  } finally {
    loading.value = false
  }
}

// 过滤掉自身及子节点（防止循环引用）
const filterSelfAndChildren = (data, id) => {
  return data.filter(item => {
    if (item.id === id) {
      return false
    }
    if (item.children && item.children.length > 0) {
      item.children = filterSelfAndChildren(item.children, id)
    }
    return true
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 确保subjectId正确设置
        formData.subjectId = props.subjectId
        
        // 根据是否编辑模式或新增模式选择API
        // 如果是编辑模式（isEdit为true且不是新增），使用PUT方法更新
        // 如果是新增模式（knowledgePoint.isNew为true或id为null），使用POST方法创建
        const isNewPoint = props.knowledgePoint.isNew || formData.id === null
        const method = (props.isEdit && !isNewPoint) ? 'put' : 'post'
        
        // 如果是新增，不需要传id
        if (method === 'post') {
          delete formData.id
        }
        
        const res = await request({
          url: '/knowledge-point',
          method,
          data: formData
        })
        
        if (res.code === 200) {
          ElMessage.success(props.isEdit ? '更新知识点成功' : '创建知识点成功')
          emit('success', formData)
          resetForm()
        } else {
          // 处理详细错误信息，优先显示data中的错误详情
          if (res.data && typeof res.data === 'object') {
            // 如果data是对象，提取所有错误信息并显示
            const errorDetails = Object.values(res.data).filter(v => v).join('，');
            if (errorDetails) {
              ElMessage.error(errorDetails);
              return;
            }
          }
          // 如果没有详细错误信息，则显示message
          ElMessage.error(res.message || (props.isEdit ? '更新知识点失败' : '创建知识点失败'))
        }
      } catch (error) {
        console.error(props.isEdit ? '更新知识点失败:' : '创建知识点失败:', error)
        ElMessage.error(props.isEdit ? '更新知识点失败，请重试' : '创建知识点失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 重置为默认值
  Object.assign(formData, {
    id: null,
    parentId: 0,
    subjectId: props.subjectId,
    name: '',
    sortOrder: 0
  })
}

// 取消操作
const cancelForm = () => {
  resetForm()
  emit('cancel')
}

// 监听知识点属性变化
watch(() => props.knowledgePoint, (newVal) => {
  if (newVal) {
    // 更新表单数据
    Object.assign(formData, {
      id: newVal.id,
      parentId: newVal.parentId || 0,
      subjectId: newVal.subjectId || props.subjectId,
      name: newVal.name || '',
      sortOrder: newVal.sortOrder || 0
    })
  }
}, { deep: true, immediate: true })

// 监听学科ID变化
watch(() => props.subjectId, (newVal) => {
  if (newVal) {
    formData.subjectId = newVal
    fetchParentOptions()
  }
})

// 组件挂载时获取父级知识点选项
fetchParentOptions()
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    v-loading="loading"
  >
    <el-form-item label="知识点名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入知识点名称" />
    </el-form-item>
    
    <el-form-item label="父级知识点" prop="parentId">
      <el-tree-select
        v-model="formData.parentId"
        :data="parentOptions"
        :render-after-expand="false"
        check-strictly
        :props="{
          value: 'id',
          label: 'name',
          children: 'children'
        }"
        placeholder="请选择父级知识点"
        class="w-100"
      />
    </el-form-item>
    
    <el-form-item label="排序序号" prop="sortOrder">
      <el-input-number v-model="formData.sortOrder" :min="0" :max="9999" />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="submitForm" :disabled="props.readonly">{{ (props.isEdit && !props.knowledgePoint.isNew) ? '更新' : '创建' }}</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.w-100 {
  width: 100%;
}
</style>